<template>
  <mu-load-more @refresh="refresh" :refreshing="refreshing" :loading="loading" @load="more">
    <slot :data="this.data" />
    <div v-if="this.data.length > 0 && pageSize * pageNumber >= total && !loading" class="dol-load-info">
      -- 已全部加载 --
    </div>
  </mu-load-more>
</template>

<script>
  //TODO 为解决当同页面修改params实时更新，加了watch。但会导致watch和created重复请求。
  export default {
    name: "Dol-load-more",
    props:{
      url: {type: String},                                  //后台地址
      method: {type: String, default: 'post'},              //请求方式
      params: {type: Object, default: () => {}},            //请求参数

      defaultPageSize: {type: Number, default: 10},         //每页条数
      defaultPageNumber: {type: Number, default: 1},        //当前页数
      itemKey: {type: String, default: '_id'},              //唯一标识
    },
    watch:{
      url(){
        this.refresh();
      },
      params(){
        if(!this.refreshing){
          this.refresh();
        }
      },
    },
    data(){
      return {
        refreshing:false,
        loading:false,
        data:[],
        total: 0,

        pageNumber: this.defaultPageNumber,
        pageSize: this.defaultPageSize,
      }
    },
    methods:{
      refresh(){
        this.pageSize = this.defaultPageSize;
        this.pageNumber = this.defaultPageNumber;
        this.data = [];
        this.refreshing = true;

        return this.load().then(result => {
          this.data = result.rows;
          this.total = result.total;
          this.refreshing = false;
          this.$emit('refresh', this.data, this.total);
          return Promise.resolve();
        });
      },
      more(){
        if(this.pageNumber * this.pageSize < this.total){
          this.pageNumber++;
          this.loading = true;
          return this.load().then(result => {
            if(this.itemKey){ //数据去重
              let i;
              for(i = 0; i < result.rows.length; ){
                if(this.data.find(item => item[this.itemKey] === result.rows[i][this.itemKey])){
                  result.rows.splice(i, 1);
                }else{
                  i++;
                }
              }
            }

            this.data = this.data.concat(result.rows);
            this.total = result.total;
            this.loading = false;
            this.$emit('more', this.data, this.total);
            return Promise.resolve();
          });
        }else{
          return Promise.resolve();
        }
      },
      load(){
        return this.$ajax({
          url: this.url,
          method: this.method,
          data:this.params,
          params:{pageSize: this.pageSize, pageNumber: this.pageNumber-1},
        });
      },
    },
    created() {
      this.refresh();
    }
  }
</script>

<style scoped>
</style>
